module.exports = (function() {
    var express = require('express');
    var router = express.Router();
    var redis = require('redis');
    var redisClient = redis.createClient();
    var config = require('./../config.json');
    var request = require('request');

    function getProjectStatus(req, res, redisKey) {
        redisClient.get(redisKey, (function(req, res) {
            return function(err, reply) {
                var url = config.apiUrl;
                if (!reply) {
                    request({
                        url: url + '/projectstatus/',
                        qs: req.params
                    }, function(error, response, body) {
                        if (!error && response.statusCode == 200) {
                            redisClient.set(redisKey, body, redis.print);
                            res.send(JSON.parse(body));
                        } else {
                            res.send('fail to load!');
                        }
                    });
                } else {
                    res.send(JSON.parse(reply));
                }
            };
        })(req, res));
    }


    router.get('/:prjId/:partitial/:forceRefresh?', function(req, res) {

        var forceRefresh = req.params.forceRefresh ? true : false;
        var partitial = req.params.partitial === 'true' ? ":partitial" : "";
        var prjId = req.params.prjId;
        var redisKey = config.redisNamespace + ":projectStatus:" + prjId.toString() + partitial;
        console.log("redisKey is %s", redisKey);
        if (forceRefresh) {
            redisClient.del(redisKey, function(rr, reply) {
                getProjectStatus(req, res, redisKey);
            });
        } else {
            getProjectStatus(req, res, redisKey);
        }

    });

    return router;
})();
